/**
 * @author lulongwen
 * Date: 2023-09-01 21:21
 * Description:
 */

import { memo, useState, useEffect } from 'react';
import { Handle, Position, NodeResizer } from 'reactflow';
import cls from 'classnames';

import type { ResizeDragEvent, ResizeParamsWithDirection } from 'reactflow';

const initState = {
  width: 100,
  height: 50,
};

const ResizableNode = (props: any) => {
  const {
    id,
    isConnectable,
    data,
    selected,
    children,
  } = props;
  const { readOnly, width, height } = data ?? {};
  // console.log('children-props', props);

  const [resize, setResize] = useState(initState);

  useEffect(() => {
    setResize(prevState => {
      return {...prevState, width, height };
    });
  }, [width, height]);

  function onResize(e: ResizeDragEvent, params: ResizeParamsWithDirection) {
    setResize(params);
  }

  const handleCls = { 'opacity-0': readOnly };


  return (
    <>
      {!readOnly && (
        <NodeResizer
          // minWidth={initState.width}
          // minHeight={initState.height}
          color='#ff0071'
          isVisible={selected}
          onResize={onResize}
          // 等比例缩放
          // keepAspectRatio
        />
      )}

      <Handle
        className={cls(handleCls)}
        type='target'
        position={Position.Top}
        onConnect={(params) => console.log('handle onConnect', params)}
        isConnectable={isConnectable}
      />
      <Handle
        className={cls(handleCls)}
        id={id}
        type='target'
        position={Position.Left}
        isConnectable={isConnectable}
      />

      <div className='relative'>
        {children({ ...resize, selected, readOnly })}
        <div
          className='flex justify-center items-center absolute w-full h-full top-0 left-0'
        >
          <span className='text-white font-medium text-xs font-mono'>
            {data?.label}
          </span>
        </div>
      </div>

      <Handle
        className={cls(handleCls)}
        type='source'
        position={Position.Right}
        isConnectable={isConnectable}
      />
      <Handle
        className={cls(handleCls)}
        id={id}
        type='source'
        position={Position.Bottom}
        isConnectable={isConnectable}
      />
    </>
  );
};

export default memo(ResizableNode);

